<template>
	<view class="page">
		<!-- Header -->
		<!-- <view class="header-bag">
			<image src="../../static/icon-back.png" class="back" @click="goBack" />
			<view class="header-center">
				<text>团购订单</text>
			</view>
		</view> -->
		
		<!-- Tab List -->
		<view class="group-list">
			<view 
				v-for="(tab, index) in tabList" 
				:key="index"
				:class="['tab-item', { active: currentTab === index }]"
				@click="switchTab(index)"
			>
				<text>{{ tab.name }}</text>
				<view class="tab-indicator"></view>
			</view>
		</view>
		
		<!-- Order List -->
		<scroll-view 
			class="order-container" 
			scroll-y="true"
			:refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- Empty State -->
			<view v-if="orderList.length === 0 && !loading" class="empty-state">
				<image src="/static/icons/kong@2x.png" class="empty-img" />
				<text class="empty-tips">订单列表为空</text>
			</view>
			
			<!-- Order Items -->
			<view v-else class="order-list">
				<view 
					v-for="(order, index) in orderList" 
					:key="index"
					class="shop-content"
				>
					<!-- Order Header -->
					<view class="order-num">
						<view class="order-number">
							<text>订单号：</text>
							<text>{{ order.order_num }}</text>
						</view>
						<view class="order-status">{{ getStatusText(order.state) }}</view>
					</view>
					
					<!-- Order Detail -->
					<view class="order-detail" @click="goToOrderDetail(order.order_num)">
						<view class="order-info">
							<image :src="imgBaseUrl + order.file_path" class="product-img" />
							<view class="order-msg">
								<text class="title">{{ order.title }}</text>
								<text class="dates">{{ order.create_time }}</text>
								<text class="num">
									数量：{{ order.num }}
									<text class="rebate">分润：<text class="fee">¥{{ order.user_rebate_total }}</text></text>
								</text>
								<text class="price">总价：<text class="price-value">￥{{ order.price }}</text></text>
							</view>
						</view>
						
						<!-- Action Button -->
						<view class="action-btn">
							<view 
								v-if="order.state === 0"
								class="btn pay-btn"
								@click.stop="showPayment(order)"
							>
								付款
							</view>
							<view 
								v-else-if="order.state === 1"
								class="btn refund-btn"
								@click.stop="applyRefund(order.order_num)"
							>
								申请退款
							</view>
							<view 
								v-else-if="order.state === 2"
								class="btn comment-btn"
								@click.stop="goToComment(order)"
							>
								评价
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- Payment Modal -->
		<view v-if="showPayModal" class="pay-modal" @click="closePayModal">
			<view class="pay-content" @click.stop>
				<view class="close-btn" @click="closePayModal"></view>
				<view class="pay-header">确认付款</view>
				<view class="pay-amount">{{ payAmount }}</view>
				
				<view class="pay-methods">
					<view class="pay-method" @click="payWithBalance">
						<text>账户余额</text>
						<text class="balance">{{ userBalance }}</text>
					</view>
					<view class="pay-method" @click="payWithWechat">
						<text>微信支付</text>
						<image src="/static/icons/icon-arrow.png" class="arrow" />
					</view>
					<view class="pay-method" @click="payWithBank">
						<text>银联支付</text>
						<image src="/static/icons/icon-arrow.png" class="arrow" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/index.js'
	import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				tabList: [
					{ name: '全部', status: 1, sel_type: 1 },
					{ name: '待付款', status: 0, sel_type: 1 },
					{ name: '待使用', status: 2, sel_type: 1 },
					{ name: '已使用', status: 3, sel_type: 1 },
					{ name: '已退款', status: 4, sel_type: 1 }
				],
				currentTab: 0,
				orderList: [],
				loading: false,
				refreshing: false,
				showPayModal: false,
				currentOrder: null,
				payAmount: '',
				userBalance: '0.00',
				imgBaseUrl: ''
			}
		},
		
		onLoad() {
			this.initData();
		},
		
		methods: {
			initData() {
				this.imgBaseUrl = getApp().globalData.imgBaseUrl || '';
				const tab = this.tabList[0];
				this.getGroupOrder(tab.status, tab.sel_type);
				this.getUserBalance();
			},
			
			switchTab(index) {
				this.currentTab = index;
				const tab = this.tabList[index];
				this.getGroupOrder(tab.status, tab.sel_type);
			},
			
			async getGroupOrder(status, sel_type = 1) {
				if (this.loading) return;
				
				this.loading = true;
				
				try {
					const res = await api.orderApi.getGroupOrderList({
						sel_type: sel_type,
						state: status,
						pages: 1
					});
					
					if (res.r === 0) {
						this.orderList = res.data.list || [];
					} else {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载订单失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.refreshing = false;
				}
			},
			
			async getUserBalance() {
				try {
					const res = await api.paymentApi.getUserBalance();
					
					if (res.r === 0) {
						this.userBalance = res.data.money;
					}
				} catch (error) {
					console.error('获取余额失败:', error);
				}
			},
			
			onRefresh() {
				this.refreshing = true;
				const tab = this.tabList[this.currentTab];
				this.getGroupOrder(tab.status, tab.sel_type);
			},
			
			getStatusText(state) {
				const statusMap = {
					0: '待付款',
					1: '待使用',
					2: '待评价',
					3: '已退款',
					4: '已评价',
					14: '已关闭'
				};
				return statusMap[state] || '未知状态';
			},
			
			showPayment(order) {
				this.currentOrder = order;
				this.payAmount = `￥${order.price}`;
				this.showPayModal = true;
			},
			
			closePayModal() {
				this.showPayModal = false;
				this.currentOrder = null;
			},
			
			async payWithBalance() {
				// 余额支付逻辑
				this.closePayModal();
				uni.showToast({
					title: '余额支付功能待实现',
					icon: 'none'
				});
			},
			
			async payWithWechat() {
				if (!this.currentOrder) return;
				
				try {
					const openid = uni.getStorageSync('openid');
					
					const res = await api.paymentApi.wechatPay({
						order_num: this.currentOrder.order_num,
						source: 5,
						type: 6,
						is_father_order: 1,
						openid: openid
					});
					
					if (res.r === 0) {
						// 微信支付逻辑
						this.handleWechatPay(res.data);
					} else {
						uni.showToast({
							title: res.msg || '支付失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('微信支付失败:', error);
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					});
				}
				
				this.closePayModal();
			},
			
			handleWechatPay(payData) {
				// 根据平台处理微信支付
				// #ifdef MP-WEIXIN
				wx.requestPayment({
					timeStamp: payData.timeStamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: (res) => {
						uni.navigateTo({
							url: `/pages/order/pay-success?type=微信支付&amount=${this.currentOrder.price}`
						});
					},
					fail: (err) => {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
				// #endif
				
				// #ifdef APP-PLUS
				// App端微信支付逻辑
				// #endif
			},
			
			payWithBank() {
				this.closePayModal();
				uni.showToast({
					title: '银联支付功能待实现',
					icon: 'none'
				});
			},
			
			async applyRefund(orderNum) {
				uni.showModal({
					title: '确认退款',
					content: '确定要申请退款吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await api.orderApi.refundGroupOrder({
									order_num: orderNum
								});
								
								if (result.r === 0) {
									uni.showToast({
										title: '退款成功！',
										icon: 'success'
									});
									// 刷新订单列表
									const tab = this.tabList[this.currentTab];
									this.getGroupOrder(tab.status, tab.sel_type);
								} else {
									uni.showToast({
										title: result.msg || '退款失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('申请退款失败:', error);
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			goToComment(order) {
				uni.navigateTo({
					url: `/pages/order/group-comment?order_num=${order.order_num}&merch_id=${order.merch_id}&group_id=${order.group_id}`
				});
			},
			
			goToOrderDetail(orderNum) {
				uni.navigateTo({
					url: `/pages/order/order-info?order_num=${orderNum}`
				});
			},
			
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss">
	.page {
		height: 100vh;
		background-color: #eeeeee;
	}
	
	.header-bag {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 88rpx;
		background: #ff1e00;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		z-index: 999;
		
		.back {
			width: 40rpx;
			height: 40rpx;
			margin-right: 20rpx;
		}
		
		.header-center {
			flex: 1;
			text-align: center;
			
			text {
				font-size: 36rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}
	
	.group-list {
		// position: fixed;
		top: 88rpx;
		left: 0;
		right: 0;
		height: 88rpx;
		background: #fff;
		display: flex;
		z-index: 998;
		
		.tab-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			position: relative;
			
			text {
				font-size: 28rpx;
				color: #333;
			}
			
			.tab-indicator {
				width: 0;
				height: 4rpx;
				background: #ff1e00;
				margin-top: 8rpx;
				transition: width 0.3s;
			}
			
			&.active {
				text {
					color: #ff1e00;
					font-weight: 500;
				}
				
				.tab-indicator {
					width: 60rpx;
				}
			}
		}
	}
	
	.order-container {
		margin-top: 176rpx;
		height: calc(100vh - 176rpx);
		padding: 20rpx;
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
		
		.empty-img {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
		}
		
		.empty-tips {
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.shop-content {
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		
		.order-num {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
			
			.order-number {
				font-size: 26rpx;
				color: #333;
			}
			
			.order-status {
				font-size: 26rpx;
				color: #ff1e00;
			}
		}
		
		.order-detail {
			padding: 30rpx;
			
			.order-info {
				display: flex;
				margin-bottom: 20rpx;
				
				.product-img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}
				
				.order-msg {
					flex: 1;
					display: flex;
					flex-direction: column;
					
					.title {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 10rpx;
						font-weight: 500;
					}
					
					.dates {
						font-size: 24rpx;
						color: #999;
						margin-bottom: 10rpx;
					}
					
					.num {
						font-size: 24rpx;
						color: #666;
						margin-bottom: 10rpx;
						
						.rebate {
							margin-left: 20rpx;
							
							.fee {
								color: #ff1e00;
							}
						}
					}
					
					.price {
						font-size: 26rpx;
						color: #333;
						
						.price-value {
							color: #ff1e00;
							font-weight: 500;
						}
					}
				}
			}
			
			.action-btn {
				display: flex;
				justify-content: flex-end;
				
				.btn {
					padding: 16rpx 32rpx;
					border-radius: 40rpx;
					font-size: 26rpx;
					text-align: center;
					min-width: 120rpx;
				}
				
				.pay-btn {
					background: #ff1e00;
					color: #fff;
				}
				
				.refund-btn, .comment-btn {
					border: 1rpx solid #6e6e6e;
					color: #6e6e6e;
					background: #fff;
				}
			}
		}
	}
	
	.pay-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: flex-end;
		z-index: 9999;
		
		.pay-content {
			width: 100%;
			background: #fff;
			border-radius: 20rpx 20rpx 0 0;
			padding: 40rpx 30rpx;
			position: relative;
			
			.close-btn {
				position: absolute;
				top: 20rpx;
				right: 30rpx;
				width: 40rpx;
				height: 40rpx;
				background: #f5f5f5;
				border-radius: 50%;
				
				&::before, &::after {
					content: '';
					position: absolute;
					top: 50%;
					left: 50%;
					width: 20rpx;
					height: 2rpx;
					background: #999;
					transform: translate(-50%, -50%) rotate(45deg);
				}
				
				&::after {
					transform: translate(-50%, -50%) rotate(-45deg);
				}
			}
			
			.pay-header {
				text-align: center;
				font-size: 32rpx;
				color: #333;
				margin-bottom: 30rpx;
				font-weight: 500;
			}
			
			.pay-amount {
				text-align: center;
				font-size: 48rpx;
				color: #ff1e00;
				margin-bottom: 40rpx;
				font-weight: bold;
			}
			
			.pay-methods {
				.pay-method {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx 0;
					border-bottom: 1rpx solid #f5f5f5;
					
					&:last-child {
						border-bottom: none;
					}
					
					text {
						font-size: 30rpx;
						color: #333;
					}
					
					.balance {
						color: #ff1e00;
					}
					
					.arrow {
						width: 24rpx;
						height: 24rpx;
					}
				}
			}
		}
	}
</style>